
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
from monitor.adb_utils.adb_command import get_cpu, get_electric_quantity, get_flow, get_pid

POINTS = 300
fig, ax = plt.subplots()
ax.set_ylim([0, 100])
ax.set_xlim([0, POINTS])
ax.set_autoscale_on(True)
ax.set_xticks([])
ax.set_yticks(range(0, 101, 10))
ax.grid(True)
# 占用内存的时间百分比
memory = [None] * POINTS
# cpu占用的时间百分比
cpu = [None] * POINTS
# 剩余电量的时间百分比
electric = [None] * POINTS
# 使用流量(g)
flow = [None] * POINTS
l_memory, = ax.plot(range(POINTS), memory, label='Memory %')
l_cpu, = ax.plot(range(POINTS), cpu, label='Cpu %')
l_electric, = ax.plot(range(POINTS), electric, label='Electric %')
l_flow, = ax.plot(range(POINTS), flow, label='Flow (g)')
ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))
bg = fig.canvas.copy_from_bbox(ax.bbox)

def OnTimer(ax, package):
    global memory, cpu, electric, flow, bg

    try:
        memory_tmp = float(get_cpu(package)[1])
        cpu_tmp = float(get_cpu(package)[0])
        electric_tmp = int(get_electric_quantity())
        flow_tmp = get_flow(get_pid(package))

        memory = memory[1:] + [memory_tmp]
        cpu = cpu[1:] + [cpu_tmp]
        electric = electric[1:] + [electric_tmp]
        flow = flow[1:] + [flow_tmp]
        l_memory.set_ydata(memory)
        l_cpu.set_ydata(cpu)
        l_electric.set_ydata(electric)
        l_flow.set_ydata(flow)
        while True:
            try:
                ax.draw_artist(l_memory)
                ax.draw_artist(l_cpu)
                ax.draw_artist(l_electric)
                ax.draw_artist(l_flow)
                break
            except:
                pass
        ax.figure.canvas.draw()
    except:
        pass

def start_monitor(package):
    timer = fig.canvas.new_timer(interval=50)
    timer.add_callback(OnTimer, ax, package)
    timer.start()
    plt.show()
    plt.savefig("./monitor/record/RealTimeMonitoring.png")














